package com.eboss2.sbs.http;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

public class HttpJsonParser {

	@SuppressWarnings({"rawtypes", "unchecked" })
	public static HttpResponse fromJson(String json) {
		Gson gson = new Gson();
		JsonObject jo = gson.fromJson(json, JsonObject.class);
		String cmd = "";
		try{cmd = jo.get("cmd").getAsString();}catch(Exception e){}
		String code = jo.get("code").getAsString();
		String msg = "";
		try{msg = jo.get("msg").getAsString();}catch(Exception e){}
		JsonElement resultElement = jo.get("result");
		String result = resultElement.isJsonNull() ? null : resultElement.getAsString();
		return new HttpResponse(cmd, code, msg, result);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> HttpResponse<T> fromJson(String json, TypeToken<T> typeToken) {
		Gson gson = new Gson();
		JsonObject jo = gson.fromJson(json, JsonObject.class);
		String cmd = "";
		try{cmd = jo.get("cmd").getAsString();}catch(Exception e){}
		String code = jo.get("code").getAsString();
		String msg = "";
		try{msg = jo.get("msg").getAsString();}catch(Exception e){}
		JsonElement resultElement = jo.get("result");
		T result = gson.fromJson(resultElement, typeToken.getType());
		return new HttpResponse(cmd, code, msg, result);
	}
	
}
